/**
 * @file service_registry_handler.cpp
 * @brief API网关服务注册处理器实现
 * @details 处理服务注册、注销、心跳等HTTP请求的具体实现
 * 
 * @author 29108
 * @date 2025/7/25
 */

#include "core_services/api_gateway/service_registry_handler.h"
#include "common/logger/logger.h"
#include <sstream>
#include <iomanip>
#include <chrono>
#include <cstdlib>
#include <algorithm>

namespace core_services {
namespace api_gateway {

    ServiceRegistryHandler::ServiceRegistryHandler(std::shared_ptr<ServiceDiscovery> service_discovery)
        : service_discovery_(service_discovery) {
        LOG_INFO("服务注册处理器初始化完成");
    }

    void ServiceRegistryHandler::registerRoutes(common::http::HttpServer* http_server) {
        if (!http_server) {
            LOG_ERROR("HTTP服务器为空，无法注册路由");
            return;
        }

        // 服务注册端点
        http_server->post("/api/v1/services/register",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceRegister(req, res);
            });

        // 服务注销端点
        http_server->del("/api/v1/services/deregister",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceDeregister(req, res);
            });

        // 服务心跳端点
        http_server->post("/api/v1/services/heartbeat",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceHeartbeat(req, res);
            });

        // 服务列表查询端点
        http_server->get("/api/v1/services",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceList(req, res);
            });

        // 服务统计信息端点
        http_server->get("/api/v1/services/stats",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceStats(req, res);
            });

        // 特定服务实时统计端点
        http_server->get("/api/v1/services/{service_name}/stats",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceRealtimeStats(req, res);
            });

        // 特定服务健康检查端点  
        http_server->get("/api/v1/services/{service_name}/health",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                this->handleServiceHealth(req, res);
            });

        // OPTIONS请求处理（CORS预检）
        http_server->options("/api/v1/services/*",
            [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                setCorsHeaders(res);
                res.setStatus(200);
                res.setBody("");
            });

        LOG_INFO("服务注册路由注册完成");
    }

    void ServiceRegistryHandler::handleServiceRegister(const common::http::HttpRequest& req, 
                                                     common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 解析请求体
            std::string request_body = req.getBody();
            if (request_body.empty()) {
                auto error_response = buildErrorResponse("EMPTY_REQUEST_BODY", "请求体不能为空");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            nlohmann::json request_json;
            try {
                request_json = nlohmann::json::parse(request_body);
            } catch (const nlohmann::json::parse_error& e) {
                auto error_response = buildErrorResponse("INVALID_JSON", "无效的JSON格式: " + std::string(e.what()));
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 验证请求格式
            if (!validateServiceRegisterRequest(request_json)) {
                auto error_response = buildErrorResponse("INVALID_REQUEST", "请求格式无效");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 构建服务信息
            auto service_info = buildServiceInfoFromJson(request_json);

            // 注册服务
            if (service_discovery_->registerService(service_info)) {
                auto success_response = buildSuccessResponse("服务注册成功", {
                    {"service_name", service_info.service_name},
                    {"host", service_info.host},
                    {"port", service_info.port}
                });
                res.setStatus(200);
                res.setBody(success_response.dump());
                
                LOG_INFO("服务注册成功: " + service_info.service_name + 
                        " (" + service_info.host + ":" + std::to_string(service_info.port) + ")");
            } else {
                auto error_response = buildErrorResponse("REGISTRATION_FAILED", "服务注册失败");
                res.setStatus(500);
                res.setBody(error_response.dump());
            }

        } catch (const std::exception& e) {
            LOG_ERROR("处理服务注册请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误");
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceDeregister(const common::http::HttpRequest& req, 
                                                       common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 解析请求体
            std::string request_body = req.getBody();
            if (request_body.empty()) {
                auto error_response = buildErrorResponse("EMPTY_REQUEST_BODY", "请求体不能为空");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            nlohmann::json request_json;
            try {
                request_json = nlohmann::json::parse(request_body);
            } catch (const nlohmann::json::parse_error& e) {
                auto error_response = buildErrorResponse("INVALID_JSON", "无效的JSON格式: " + std::string(e.what()));
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 验证必需字段
            if (!request_json.contains("service_name") || !request_json.contains("host") || !request_json.contains("port")) {
                auto error_response = buildErrorResponse("MISSING_FIELDS", "缺少必需字段: service_name, host, port");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            std::string service_name = request_json["service_name"];
            std::string host = request_json["host"];
            int port = request_json["port"];

            // 注销服务
            if (service_discovery_->deregisterService(service_name, host, port)) {
                auto success_response = buildSuccessResponse("服务注销成功", {
                    {"service_name", service_name},
                    {"host", host},
                    {"port", port}
                });
                res.setStatus(200);
                res.setBody(success_response.dump());
                
                LOG_INFO("服务注销成功: " + service_name + " (" + host + ":" + std::to_string(port) + ")");
            } else {
                auto error_response = buildErrorResponse("DEREGISTRATION_FAILED", "服务注销失败或服务不存在");
                res.setStatus(404);
                res.setBody(error_response.dump());
            }

        } catch (const std::exception& e) {
            LOG_ERROR("处理服务注销请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误");
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceHeartbeat(const common::http::HttpRequest& req, 
                                                      common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 解析请求体
            std::string request_body = req.getBody();
            if (request_body.empty()) {
                auto error_response = buildErrorResponse("EMPTY_REQUEST_BODY", "请求体不能为空");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            nlohmann::json request_json;
            try {
                request_json = nlohmann::json::parse(request_body);
            } catch (const nlohmann::json::parse_error& e) {
                auto error_response = buildErrorResponse("INVALID_JSON", "无效的JSON格式: " + std::string(e.what()));
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 验证必需字段
            if (!request_json.contains("service_name") || !request_json.contains("host") || !request_json.contains("port")) {
                auto error_response = buildErrorResponse("MISSING_FIELDS", "缺少必需字段: service_name, host, port");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            std::string service_name = request_json["service_name"];
            std::string host = request_json["host"];
            int port = request_json["port"];

            // 构建服务信息对象，包含metadata更新
            ServiceDiscovery::ServiceInfo service_info;
            service_info.service_name = service_name;
            service_info.host = host;
            service_info.port = port;
            service_info.healthy = request_json.value("status", "healthy") == "healthy";
            
            // 处理metadata更新 - 这是关键修复！
            if (request_json.contains("metadata") && request_json["metadata"].is_object()) {
                service_info.metadata.clear(); // 清空现有metadata
                for (auto it = request_json["metadata"].begin(); it != request_json["metadata"].end(); ++it) {
                    if (it.value().is_string()) {
                        service_info.metadata[it.key()] = it.value();
                    } else if (it.value().is_number()) {
                        service_info.metadata[it.key()] = std::to_string(it.value().get<double>());
                    } else if (it.value().is_boolean()) {
                        service_info.metadata[it.key()] = it.value().get<bool>() ? "true" : "false";
                    } else if (it.value().is_array()) {
                        service_info.metadata[it.key()] = it.value().dump();
                    }
                }
                LOG_DEBUG("心跳更新metadata，服务: " + service_name + ", metadata条目: " + std::to_string(service_info.metadata.size()));
            }

            // 使用增强的心跳更新方法
            if (service_discovery_->updateHeartbeatWithMetadata(service_name, host, port, service_info)) {
                auto success_response = buildSuccessResponse("心跳和metadata更新成功", {
                    {"service_name", service_name},
                    {"metadata_entries", service_info.metadata.size()}
                });
                res.setStatus(200);
                res.setBody(success_response.dump());
                
                LOG_INFO("服务心跳和metadata更新成功: " + service_name + " (" + host + ":" + std::to_string(port) + ")");
            } else {
                auto error_response = buildErrorResponse("HEARTBEAT_FAILED", "心跳更新失败或服务不存在");
                res.setStatus(404);
                res.setBody(error_response.dump());
                
                LOG_WARNING("服务心跳更新失败: " + service_name + " (" + host + ":" + std::to_string(port) + ")");
            }

        } catch (const std::exception& e) {
            LOG_ERROR("处理服务心跳请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误");
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceList(const common::http::HttpRequest& req, 
                                                 common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 获取查询参数
            std::string service_name = req.getQueryParam("service");
            std::string game_type = req.getQueryParam("game_type");
            bool healthy_only = req.getQueryParam("healthy") == "true";

            nlohmann::json services_json = nlohmann::json::array();
            std::vector<ServiceDiscovery::ServiceInfo> services;

            // 根据不同的查询条件获取服务列表
            if (!game_type.empty()) {
                // 按游戏类型查询
                services = service_discovery_->getServicesByGameType(game_type, healthy_only);
                LOG_INFO("按游戏类型查询服务: " + game_type + ", 健康状态筛选: " + (healthy_only ? "true" : "false"));
            } else if (!service_name.empty()) {
                // 按服务名称查询
                services = healthy_only ? 
                    service_discovery_->getHealthyServices(service_name) :
                    service_discovery_->getServices(service_name);
                LOG_INFO("按服务名称查询: " + service_name + ", 健康状态筛选: " + (healthy_only ? "true" : "false"));
            } else {
                // 查询所有服务
                services = service_discovery_->getAllServices(healthy_only);
                LOG_INFO("查询所有服务, 健康状态筛选: " + std::string(healthy_only ? "true" : "false"));
            }

            // 将服务信息转换为JSON
            for (const auto& service : services) {
                services_json.push_back(serviceInfoToJson(service));
            }

            // 构建响应
            auto success_response = buildSuccessResponse("查询成功", {
                {"services", services_json},
                {"count", services_json.size()},
                {"filters", {
                    {"service_name", service_name},
                    {"game_type", game_type},
                    {"healthy_only", healthy_only}
                }}
            });
            res.setStatus(200);
            res.setBody(success_response.dump());

            LOG_INFO("服务列表查询完成，返回 " + std::to_string(services.size()) + " 个服务");

        } catch (const std::exception& e) {
            LOG_ERROR("处理服务列表请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误: " + std::string(e.what()));
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceStats(const common::http::HttpRequest& req, 
                                                  common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            auto stats = service_discovery_->getServiceStats();
            nlohmann::json stats_json;
            for (const auto& [key, value] : stats) {
                stats_json[key] = value;
            }

            auto success_response = buildSuccessResponse("统计信息获取成功", stats_json);
            res.setStatus(200);
            res.setBody(success_response.dump());

        } catch (const std::exception& e) {
            LOG_ERROR("处理服务统计请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误");
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceRealtimeStats(const common::http::HttpRequest& req, 
                                                          common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 从URL路径中提取service_name
            std::string path = req.getPath();
            std::string service_name = extractServiceNameFromPath(path);
            
            if (service_name.empty()) {
                auto error_response = buildErrorResponse("INVALID_SERVICE_NAME", "无效的服务名称");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 获取服务列表
            auto services = service_discovery_->getServices(service_name);
            if (services.empty()) {
                auto error_response = buildErrorResponse("SERVICE_NOT_FOUND", "服务不存在: " + service_name);
                res.setStatus(404);
                res.setBody(error_response.dump());
                return;
            }

            // 构建实时统计响应
            nlohmann::json realtime_stats = nlohmann::json::object();
            
            // 如果是游戏服务，获取详细的游戏统计信息
            if (isGameService(service_name)) {
                realtime_stats = buildGameServiceStats(services[0]);
            } else {
                realtime_stats = buildGeneralServiceStats(services[0]);
            }

            auto success_response = buildSuccessResponse("实时统计获取成功", {
                {"service_name", service_name},
                {"realtime_stats", realtime_stats},
                {"last_updated", getCurrentTimestamp()}
            });
            
            res.setStatus(200);
            res.setBody(success_response.dump());

            LOG_INFO("实时统计查询完成: " + service_name);

        } catch (const std::exception& e) {
            LOG_ERROR("处理实时统计请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误: " + std::string(e.what()));
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    void ServiceRegistryHandler::handleServiceHealth(const common::http::HttpRequest& req, 
                                                   common::http::HttpResponse& res) {
        try {
            setCorsHeaders(res);
            setJsonHeaders(res);

            // 从URL路径中提取service_name
            std::string path = req.getPath();
            std::string service_name = extractServiceNameFromPath(path);
            
            if (service_name.empty()) {
                auto error_response = buildErrorResponse("INVALID_SERVICE_NAME", "无效的服务名称");
                res.setStatus(400);
                res.setBody(error_response.dump());
                return;
            }

            // 获取服务列表
            auto services = service_discovery_->getServices(service_name);
            if (services.empty()) {
                auto error_response = buildErrorResponse("SERVICE_NOT_FOUND", "服务不存在: " + service_name);
                res.setStatus(404);
                res.setBody(error_response.dump());
                return;
            }

            // 构建健康检查响应
            nlohmann::json health_status = buildHealthCheckResponse(services[0]);

            auto success_response = buildSuccessResponse("健康检查完成", health_status);
            res.setStatus(200);
            res.setBody(success_response.dump());

            LOG_INFO("健康检查完成: " + service_name);

        } catch (const std::exception& e) {
            LOG_ERROR("处理健康检查请求异常: " + std::string(e.what()));
            auto error_response = buildErrorResponse("INTERNAL_ERROR", "内部服务器错误: " + std::string(e.what()));
            res.setStatus(500);
            res.setBody(error_response.dump());
        }
    }

    nlohmann::json ServiceRegistryHandler::buildSuccessResponse(const std::string& message,
                                                              const nlohmann::json& data) {
        nlohmann::json response;
        response["success"] = true;
        response["message"] = message;
        response["timestamp"] = std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::system_clock::now().time_since_epoch()).count();

        if (!data.empty()) {
            response["data"] = data;
        }

        return response;
    }

    nlohmann::json ServiceRegistryHandler::buildErrorResponse(const std::string& error_code,
                                                            const std::string& error_message) {
        nlohmann::json response;
        response["success"] = false;
        response["error_code"] = error_code;
        response["error_message"] = error_message;
        response["timestamp"] = std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::system_clock::now().time_since_epoch()).count();

        return response;
    }

    bool ServiceRegistryHandler::validateServiceRegisterRequest(const nlohmann::json& request_json) {
        // 检查必需字段
        if (!request_json.contains("service_name") || !request_json.contains("host") ||
            !request_json.contains("port")) {
            return false;
        }

        // 检查字段类型
        if (!request_json["service_name"].is_string() ||
            !request_json["host"].is_string() ||
            !request_json["port"].is_number_integer()) {
            return false;
        }

        // 检查端口范围
        int port = request_json["port"];
        if (port <= 0 || port > 65535) {
            return false;
        }

        return true;
    }

    ServiceDiscovery::ServiceInfo ServiceRegistryHandler::buildServiceInfoFromJson(const nlohmann::json& json) {
        ServiceDiscovery::ServiceInfo service_info;

        service_info.service_name = json["service_name"];
        service_info.host = json["host"];
        service_info.port = json["port"];

        // 可选字段
        if (json.contains("service_version")) {
            service_info.service_version = json["service_version"];
        }

        if (json.contains("health_check_endpoint")) {
            service_info.health_check_endpoint = json["health_check_endpoint"];
        }

        if (json.contains("weight")) {
            service_info.weight = json["weight"];
        }

        if (json.contains("endpoints") && json["endpoints"].is_array()) {
            for (const auto& endpoint : json["endpoints"]) {
                if (endpoint.is_string()) {
                    service_info.endpoints.push_back(endpoint);
                }
            }
        }

        if (json.contains("metadata") && json["metadata"].is_object()) {
            for (auto it = json["metadata"].begin(); it != json["metadata"].end(); ++it) {
                if (it.value().is_string()) {
                    service_info.metadata[it.key()] = it.value();
                } else if (it.value().is_number()) {
                    service_info.metadata[it.key()] = std::to_string(it.value().get<double>());
                } else if (it.value().is_boolean()) {
                    service_info.metadata[it.key()] = it.value().get<bool>() ? "true" : "false";
                }
            }
        }

        return service_info;
    }

    nlohmann::json ServiceRegistryHandler::serviceInfoToJson(const ServiceDiscovery::ServiceInfo& service_info) {
        nlohmann::json json;

        json["service_name"] = service_info.service_name;
        json["service_version"] = service_info.service_version;
        json["host"] = service_info.host;
        json["port"] = service_info.port;
        json["health_check_endpoint"] = service_info.health_check_endpoint;
        json["healthy"] = service_info.healthy;
        json["weight"] = service_info.weight;

        json["endpoints"] = nlohmann::json::array();
        for (const auto& endpoint : service_info.endpoints) {
            json["endpoints"].push_back(endpoint);
        }

        json["metadata"] = nlohmann::json::object();
        for (const auto& [key, value] : service_info.metadata) {
            json["metadata"][key] = value;
        }

        json["last_heartbeat"] = std::chrono::duration_cast<std::chrono::seconds>(
            service_info.last_heartbeat.time_since_epoch()).count();

        return json;
    }

    void ServiceRegistryHandler::setCorsHeaders(common::http::HttpResponse& res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        res.setHeader("Access-Control-Max-Age", "86400");
    }

    void ServiceRegistryHandler::setJsonHeaders(common::http::HttpResponse& res) {
        res.setHeader("Content-Type", "application/json; charset=utf-8");
    }

    std::string ServiceRegistryHandler::extractServiceNameFromPath(const std::string& path) {
        // 解析路径格式: /api/v1/services/{service_name}/stats 或 /api/v1/services/{service_name}/health
        std::string prefix = "/api/v1/services/";
        size_t prefix_pos = path.find(prefix);
        if (prefix_pos == std::string::npos) {
            return "";
        }
        
        size_t start = prefix_pos + prefix.length();
        size_t end = path.find('/', start);
        if (end == std::string::npos) {
            end = path.length();
        }
        
        if (start >= end) {
            return "";
        }
        
        return path.substr(start, end - start);
    }

    bool ServiceRegistryHandler::isGameService(const std::string& service_name) {
        // 检查服务名称是否包含游戏相关关键词
        return service_name.find("game") != std::string::npos ||
               service_name.find("snake") != std::string::npos ||
               service_name.find("tetris") != std::string::npos ||
               service_name.find("puzzle") != std::string::npos;
    }

    nlohmann::json ServiceRegistryHandler::buildGameServiceStats(const ServiceDiscovery::ServiceInfo& service_info) {
        nlohmann::json stats = nlohmann::json::object();
        
        // 从metadata中提取游戏服务的实时统计信息
        if (service_info.metadata.find("current_players") != service_info.metadata.end()) {
            stats["current_players"] = std::stoi(service_info.metadata.at("current_players"));
        } else {
            stats["current_players"] = 0;
        }
        
        if (service_info.metadata.find("max_players") != service_info.metadata.end()) {
            stats["max_players"] = std::stoi(service_info.metadata.at("max_players"));
        } else {
            stats["max_players"] = 100;
        }
        
        if (service_info.metadata.find("active_rooms") != service_info.metadata.end()) {
            stats["active_rooms"] = std::stoi(service_info.metadata.at("active_rooms"));
        } else {
            stats["active_rooms"] = 0;
        }
        
        if (service_info.metadata.find("cpu_usage") != service_info.metadata.end()) {
            stats["cpu_usage_percent"] = std::stod(service_info.metadata.at("cpu_usage"));
        } else {
            stats["cpu_usage_percent"] = 0.0;
        }
        
        if (service_info.metadata.find("memory_usage") != service_info.metadata.end()) {
            stats["memory_usage_percent"] = std::stod(service_info.metadata.at("memory_usage"));
        } else {
            stats["memory_usage_percent"] = 0.0;
        }
        
        if (service_info.metadata.find("ping_average") != service_info.metadata.end()) {
            stats["response_time_ms"] = std::stod(service_info.metadata.at("ping_average"));
        } else {
            stats["response_time_ms"] = 0.0;
        }
        
        // 计算负载百分比
        if (stats.contains("current_players") && stats.contains("max_players")) {
            int current = stats["current_players"];
            int max_val = stats["max_players"];
            if (max_val > 0) {
                double player_load = (static_cast<double>(current) / max_val) * 100.0;
                double cpu_load = stats.value("cpu_usage_percent", 0.0);
                double memory_load = stats.value("memory_usage_percent", 0.0);
                
                // 加权平均：玩家数50%，CPU 30%，内存20%
                stats["load_percentage"] = (player_load * 0.5) + (cpu_load * 0.3) + (memory_load * 0.2);
            } else {
                stats["load_percentage"] = 0.0;
            }
        }
        
        // 游戏特定统计
        if (service_info.metadata.find("game_type") != service_info.metadata.end()) {
            stats["game_type"] = service_info.metadata.at("game_type");
        }
        
        if (service_info.metadata.find("region") != service_info.metadata.end()) {
            stats["region"] = service_info.metadata.at("region");
        }
        
        // 获取最近玩家数变化（基于实际数据）
        nlohmann::json player_history = nlohmann::json::array();
        // 注意：这里应该从实际的监控数据源获取历史数据
        // 暂时返回空数组，等待实际监控系统集成
        // TODO: 集成实际的监控数据源
        stats["players_last_hour"] = player_history;
        
        // 游戏模式分布（模拟数据）
        if (stats.contains("active_rooms") && stats["active_rooms"].get<int>() > 0) {
            int active_rooms = stats["active_rooms"];
            stats["rooms_by_mode"] = {
                {"classic", std::max(1, active_rooms * 3 / 4)},
                {"speed", std::max(0, active_rooms / 5)},
                {"survival", std::max(0, active_rooms - (active_rooms * 3 / 4) - (active_rooms / 5))}
            };
            
            if (stats.contains("current_players") && stats["current_players"].get<int>() > 0) {
                stats["average_room_size"] = static_cast<double>(stats["current_players"]) / active_rooms;
            }
        }
        
        // 今日游戏统计（模拟数据）
        stats["games_completed_today"] = rand() % 200 + 50;
        stats["average_game_duration_minutes"] = 8.5 + (rand() % 30) / 10.0;
        int current_players = stats.value("current_players", 0);
        stats["peak_players_today"] = std::max(current_players, current_players + rand() % 50);
        
        return stats;
    }

    nlohmann::json ServiceRegistryHandler::buildGeneralServiceStats(const ServiceDiscovery::ServiceInfo& service_info) {
        nlohmann::json stats = nlohmann::json::object();
        
        // 基本统计信息
        stats["service_name"] = service_info.service_name;
        stats["healthy"] = service_info.healthy;
        stats["weight"] = service_info.weight;
        
        // 性能统计
        if (service_info.metadata.find("cpu_usage") != service_info.metadata.end()) {
            stats["cpu_usage_percent"] = std::stod(service_info.metadata.at("cpu_usage"));
        }
        
        if (service_info.metadata.find("memory_usage") != service_info.metadata.end()) {
            stats["memory_usage_percent"] = std::stod(service_info.metadata.at("memory_usage"));
        }
        
        // 连接统计
        if (service_info.metadata.find("active_connections") != service_info.metadata.end()) {
            stats["active_connections"] = std::stoi(service_info.metadata.at("active_connections"));
        }
        
        // 请求统计
        if (service_info.metadata.find("requests_per_second") != service_info.metadata.end()) {
            stats["requests_per_second"] = std::stod(service_info.metadata.at("requests_per_second"));
        }
        
        return stats;
    }

    nlohmann::json ServiceRegistryHandler::buildHealthCheckResponse(const ServiceDiscovery::ServiceInfo& service_info) {
        nlohmann::json health = nlohmann::json::object();
        
        // 整体健康状态
        health["status"] = service_info.healthy ? "healthy" : "unhealthy";
        
        // 各组件健康检查
        nlohmann::json checks = nlohmann::json::object();
        
        // 基础检查
        checks["service"] = service_info.healthy ? "healthy" : "unhealthy";
        
        // 如果是游戏服务，添加游戏特定检查
        if (isGameService(service_info.service_name)) {
            // WebSocket连接检查
            checks["websocket"] = "healthy"; // 基于服务是否在线
            
            // 数据库连接检查（基于服务健康状态）
            checks["database"] = service_info.healthy ? "healthy" : "unhealthy";
            
            // 内存和CPU检查
            if (service_info.metadata.find("memory_usage") != service_info.metadata.end()) {
                double memory_usage = std::stod(service_info.metadata.at("memory_usage"));
                if (memory_usage > 90.0) {
                    checks["memory"] = "critical";
                } else if (memory_usage > 80.0) {
                    checks["memory"] = "warning";
                } else {
                    checks["memory"] = "healthy";
                }
            }
            
            if (service_info.metadata.find("cpu_usage") != service_info.metadata.end()) {
                double cpu_usage = std::stod(service_info.metadata.at("cpu_usage"));
                if (cpu_usage > 90.0) {
                    checks["cpu"] = "critical";
                } else if (cpu_usage > 80.0) {
                    checks["cpu"] = "warning";
                } else {
                    checks["cpu"] = "healthy";
                }
            }
        }
        
        health["checks"] = checks;
        
        // 详细信息
        nlohmann::json details = nlohmann::json::object();
        auto now = std::chrono::system_clock::now();
        auto heartbeat_diff = std::chrono::duration_cast<std::chrono::seconds>(
            now - service_info.last_heartbeat).count();
        details["uptime_seconds"] = heartbeat_diff > 0 ? heartbeat_diff : 0;
        details["last_heartbeat"] = std::chrono::duration_cast<std::chrono::seconds>(
            service_info.last_heartbeat.time_since_epoch()).count();
        details["version"] = service_info.service_version;
        details["host"] = service_info.host;
        details["port"] = service_info.port;
        
        health["details"] = details;
        
        return health;
    }

    std::string ServiceRegistryHandler::getCurrentTimestamp() {
        auto now = std::chrono::system_clock::now();
        auto time_t = std::chrono::system_clock::to_time_t(now);
        auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
            now.time_since_epoch()) % 1000;
        
        std::stringstream ss;
        ss << std::put_time(std::gmtime(&time_t), "%Y-%m-%dT%H:%M:%S");
        ss << '.' << std::setfill('0') << std::setw(3) << ms.count() << 'Z';
        return ss.str();
    }

} // namespace api_gateway
} // namespace core_services
